source ${INPUT_1}

OUTPUTSHARED=$shareddir

JOBWD=`pwd`

echo "Meshing_$COUNTER : $JOBWD" >> $OUTPUTSHARED/worklfow-jobs.txt


echo "loading modules for meshing"
#module purge
#module load intel/13.1.0
#module load intelmpi/4.1.3
#module load mkl/11.0.2
#module load hypre/2.9.0b
#module load mumps/4.10.0
#module load trilinos/11.0.3
#module load elmer/latest
module load python-env/2.7.3
module load gmsh
module elmer-env/latest
echo "loading module done.."





echo "creating soft link"
[[ -e $JOBWD/input ]] || ln -sv $STORAGESHARED/input $JOBWD/input


[[ -e $JOBWD/n_list.txt ]] || ln -sv $STORAGESHARED/n_list.txt $JOBWD/n_list.txt
[[ -e $JOBWD/ParticleResults ]] || ln -sv $STORAGESHARED/ParticleResults $JOBWD/ParticleResults


first=`awk 'NR==1 {print $1}' n_list.txt`

NR=`sed -n -e "$((COUNTER+1))p" n_list.txt`

nb=`awk '{print $1}' <<< $NR`

echo CURRENT-ITERATIVE-VALUE $nb

mkdir -p priorbeta/$nb

mkdir -p Python_particle_n/Date$nb

mkdir -p ElmerResults/Date$nb

mkdir -p $JOBWD/surf/0/

#cp -f $STORAGESHARED/input/dem_surf_bed/surf${first}_elmer.xyz $JOBWD/surf/$first/surf.xyz

#[[ -e $JOBWD/surf/$first/surf.xyz ]] || ln -sv $STORAGESHARED/input/dem_surf_bed/surf${first}_elmer.xyz $JOBWD/surf/$first/surf.xyz

[[ -e $JOBWD/surf/0/surf.xyz ]] || ln -sv $STORAGESHARED/input/dem_surf_bed/surf0_elmer.xyz $JOBWD/surf/0/surf.xyz




firstIteration=true
nrbefore=0
nb_before=0

currentctr=$((COUNTER+1))

echo "COUNTER VARIABLE ::: $COUNTER"
echo "current counter ::: $currentctr"

if [ $currentctr -gt 1 ]; then
  echo "current ctr greater than one"
  nrbefore=`sed -n -e "$((COUNTER))p" $JOBWD/input/n_list.bak`
  nb_before=`awk '{print $1}' <<< $nrbefore`
  firstIteration=false
  echo "previous iteration element ::::  $nb_before"
fi


#if  $firstIteration 
if [ $nb -eq 0 ]
then
    echo "first iteration reached...." 
    n=0
    mkdir -p $OUTPUTSHARED/Mesh
else
    echo "link surf..."
    n=$nb
    # copying previous produced Mesh
    #cp -rv $OUTPUTSHARED/Mesh $JOBWD/
    #[[ -e $JOBWD/surf/$nb_before ]] || ln -sv $OUTPUTSHARED/surf/$nb_before $JOBWD/surf/$nb_before
    #echo "executed nb before"
    [[ -e $JOBWD/surf/$nb ]] || ln -sv $OUTPUTSHARED/surf/$nb $JOBWD/surf/$nb
    echo "executed nb"
fi

#echo "n value is $n"


## you need to copy, otherwise python execution will 
cp -rv $STORAGESHARED/input/ClassProperties-Template.py $JOBWD/input/Python_particle/ClassProperties.py
echo "modifying ClassProperties.py self.path_folder.."
sed -i -e 's|@@CWD@@|'${JOBWD}'|g' $JOBWD/input/Python_particle/ClassProperties.py

echo " python starts..."
python $JOBWD/input/Python_particle/MeshToElmer.py $nb $JOBWD
echo " python ends..."

rm -rf $OUTPUTSHARED/Mesh/mesh$nb
mv Mesh/mesh$nb $OUTPUTSHARED/Mesh
echo "moved.."

cp $STANDARD_OUT $OUTPUTSHARED/Mesh/stdout_$nb
cp $STANDARD_ERROR $OUTPUTSHARED/Mesh/stderr_$nb

